class SubtitleContentManager {
  constructor() {
    // 内部存储的当前字幕文本
    this.currentText = '';
    // 画布渲染器引用
    this.canvasRenderer = null;
    // 纹理平面管理器引用
    this.texturePlaneManager = null;
    // 事件监听器存储
    this.listeners = {};
    // 音频管理器引用 - 用于同步字幕
    this.audioManager = null;
    // 当前句子队列
    this.sentences = [];
    // 当前句子索引
    this.currentSentenceIndex = 0;
    // 句子时间戳信息
    this.sentenceTimestamps = [];
    // 当前正在处理的完整文本
    this.fullText = '';
    // 音频总时长
    this.audioDuration = 0;
    // 是否正在进行同步播放
    this.isSyncing = false;
    // 音频进度监听器引用
    this.audioProgressListener = null;
    
    console.log('SubtitleContentManager initialized with sync capability');
  }
  
  /**
   * 设置画布渲染器引用
   * @param {CanvasRenderer} renderer - 画布渲染器实例
   */
  setCanvasRenderer(renderer) {
    this.canvasRenderer = renderer;
  }
  
  /**
   * 设置纹理平面管理器引用
   * @param {TexturePlaneManager} manager - 纹理平面管理器实例
   */
  setTexturePlaneManager(manager) {
    this.texturePlaneManager = manager;
  }
  
  /**
   * 更新字幕内容
   * @param {string} text - 字幕文本
   */
  updateContent(text) {
    this.currentText = text;
    this._dispatchEvent('contentUpdated', { text });
    
    if (text && text.trim() !== '') {
      // 如果文本不为空，向Canvas渲染器发送绘制指令
      if (this.canvasRenderer) {
        this.canvasRenderer.drawText(text);
      }
      
      // 确保同时更新3D纹理，使字幕在XR环境中显示
      if (this.texturePlaneManager) {
        this.texturePlaneManager.updateTexture();
        this.texturePlaneManager.showSubtitle();
      }
    } else {
      // 如果文本为空，向纹理平面管理器发送隐藏指令
      if (this.texturePlaneManager) {
        this.texturePlaneManager.hideSubtitle();
      }
    }
    
    console.log('Subtitle content updated:', text.length > 0 ? text.substring(0, 30) + '...' : 'empty');
  }
  
  /**
   * 获取当前字幕内容
   * @returns {string} 当前字幕文本
   */
  getCurrentContent() {
    return this.currentText;
  }
  
  /**
   * 清除字幕内容
   */
  clear() {
    this.updateContent('');
  }
  
  /**
   * 添加事件监听器
   * @param {string} eventName - 事件名称
   * @param {Function} callback - 回调函数
   */
  addEventListener(eventName, callback) {
    if (!this.listeners[eventName]) {
      this.listeners[eventName] = [];
    }
    this.listeners[eventName].push(callback);
  }
  
  /**
   * 移除事件监听器
   * @param {string} eventName - 事件名称
   * @param {Function} callback - 回调函数
   */
  removeEventListener(eventName, callback) {
    if (this.listeners[eventName]) {
      this.listeners[eventName] = this.listeners[eventName].filter(cb => cb !== callback);
    }
  }
  
  /**
   * 内部事件分发方法
   * @param {string} eventName - 事件名称
   * @param {Object} eventData - 事件数据
   */
  _dispatchEvent(eventName, eventData) {
    if (this.listeners[eventName]) {
      this.listeners[eventName].forEach(callback => {
        try {
          callback(eventData);
        } catch (error) {
          console.error(`Error in subtitle event listener:`, error);
        }
      });
    }
  }
  
  /**
   * 连接到语音识别管理器
   * @param {VoiceManager} voiceManager - 语音识别管理器实例
   */
  connectToVoiceManager(voiceManager) {
    if (!voiceManager) {
      console.warn('VoiceManager not available for subtitle connection');
      return;
    }
    
    // 监听语音识别结果
    voiceManager.addEventListener('recognitionResult', (event) => {
      if (event.text) {
        this.updateContent(event.text);
      }
    });
    
    // 监听语音结束事件，可选择在语音结束后清除字幕
    voiceManager.addEventListener('speechEnd', () => {
      // 可以在这里添加延迟清除逻辑
      // setTimeout(() => this.clear(), 3000);
    });
    
    console.log('SubtitleContentManager connected to VoiceManager');
  }
  
  /**
   * 连接到音频管理器，用于同步字幕
   * @param {AudioManager} audioManager - 音频管理器实例
   */
  connectToAudioManager(audioManager) {
    if (!audioManager) {
      console.warn('AudioManager not available for subtitle sync');
      return;
    }
    
    this.audioManager = audioManager;
    
    // 监听音频结束事件，重置同步状态
    audioManager.on('end', () => {
      this._resetSyncState();
    });
    
    console.log('SubtitleContentManager connected to AudioManager for syncing');
  }
  
  /**
   * 更新字幕内容，支持同步播放模式
   * @param {string} text - 字幕文本
   * @param {number} duration - 音频总时长（秒）
   * @param {boolean} syncWithAudio - 是否与音频同步
   */
  updateContent(text, duration = 0, syncWithAudio = false) {
    this.currentText = text;
    this.fullText = text;
    this._dispatchEvent('contentUpdated', { text });
    
    if (!text || text.trim() === '') {
      // 如果文本为空，隐藏字幕
      if (this.texturePlaneManager) {
        this.texturePlaneManager.hideSubtitle();
      }
      this._resetSyncState();
      console.log('Subtitle cleared');
      return;
    }
    
    if (syncWithAudio && duration > 0 && this.audioManager) {
      // 启用与音频同步的逐句显示模式
      this._setupSyncMode(text, duration);
    } else {
      // 常规模式：一次性显示完整文本
      if (this.canvasRenderer) {
        this.canvasRenderer.drawText(text);
      }
      
      // 确保同时更新3D纹理，使字幕在XR环境中显示
      if (this.texturePlaneManager) {
        this.texturePlaneManager.updateTexture();
        this.texturePlaneManager.showSubtitle();
      }
    }
    
    console.log('Subtitle content updated:', text.length > 0 ? text.substring(0, 30) + '...' : 'empty');
  }
  
  /**
   * 设置同步模式，准备逐句显示
   * @private
   * @param {string} text - 完整文本
   * @param {number} duration - 音频总时长（秒）
   */
  _setupSyncMode(text, duration) {
    // 重置之前的同步状态
    this._resetSyncState();
    
    // 分割句子
    this.sentences = this._splitIntoSentences(text);
    this.audioDuration = duration;
    this.isSyncing = true;
    
    console.log(`Set up sync mode with ${this.sentences.length} sentences, duration: ${duration}s`);
    
    // 基于句子数量平均分配时间戳
    this._calculateSentenceTimestamps();
    
    // 设置音频进度监听器
    this._setupAudioProgressListener();
    
    // 显示第一句
    this._showCurrentSentence();
  }
  
  /**
   * 将文本分割为句子
   * @private
   * @param {string} text - 完整文本
   * @returns {string[]} 句子数组
   */
  _splitIntoSentences(text) {
    if (!text || text.trim() === '') return [];
    
    // 改进的句子分割逻辑，支持中英文标点和引号等特殊情况
    // 分割规则：中文句号、感叹号、问号，英文句号、感叹号、问号，并且忽略引号内的分割符
    const sentences = [];
    const sentenceEndRegex = /([。！？.!?])(?![^"']*["'](?!")(?!'))/g;
    let lastIndex = 0;
    let match;
    
    while ((match = sentenceEndRegex.exec(text)) !== null) {
      // 提取句子（包括结束标点）
      const sentence = text.substring(lastIndex, match.index + 1).trim();
      if (sentence.length > 0) {
        sentences.push(sentence);
      }
      lastIndex = match.index + 1;
    }
    
    // 处理最后一个句子（如果有）
    const lastSentence = text.substring(lastIndex).trim();
    if (lastSentence.length > 0) {
      sentences.push(lastSentence);
    }
    
    // 如果没有使用正则分割成功，使用备用方法
    if (sentences.length === 0) {
      // 对于没有明显句子分隔符的长文本，按照合理长度分段
      return this._splitLongText(text);
    }
    
    return sentences;
  }
  
  /**
   * 将长文本分割为合理长度的段落
   * @private
   * @param {string} text - 长文本
   * @returns {string[]} 段落数组
   */
  _splitLongText(text) {
    const paragraphs = [];
    const maxLength = 30; // 每个段落的最大字符数
    
    // 尝试在空格或标点处分割，避免破坏词语
    let startIndex = 0;
    while (startIndex < text.length) {
      let endIndex = Math.min(startIndex + maxLength, text.length);
      
      // 如果不是最后一段，尝试在空格或标点处分割
      if (endIndex < text.length) {
        // 向前查找最近的空格或标点
        while (endIndex > startIndex && !/[\s，,；;]/.test(text[endIndex])) {
          endIndex--;
        }
        
        // 如果没找到合适的分割点，就用最大长度
        if (endIndex === startIndex) {
          endIndex = startIndex + maxLength;
        }
      }
      
      const paragraph = text.substring(startIndex, endIndex).trim();
      if (paragraph.length > 0) {
        paragraphs.push(paragraph);
      }
      
      startIndex = endIndex;
    }
    
    return paragraphs;
  }
  
  /**
   * 计算每个句子的时间戳
   * @private
   */
  _calculateSentenceTimestamps() {
    if (this.sentences.length === 0 || this.audioDuration <= 0) {
      return;
    }
    
    // 基于句子长度动态分配时间，而不是平均分配
    const sentenceCount = this.sentences.length;
    
    // 计算每个句子的字符数
    const lengths = this.sentences.map(s => s.length);
    const totalLength = lengths.reduce((sum, len) => sum + len, 0);
    
    this.sentenceTimestamps = [];
    let currentTime = 0;
    
    for (let i = 0; i < sentenceCount; i++) {
      // 基于句子长度比例分配时间
      const sentenceDuration = (lengths[i] / totalLength) * this.audioDuration;
      
      this.sentenceTimestamps.push({
        start: currentTime,
        end: currentTime + sentenceDuration,
        text: this.sentences[i]
      });
      
      currentTime += sentenceDuration;
    }
    
    // 确保最后一句的结束时间不超过总时长
    if (this.sentenceTimestamps.length > 0) {
      this.sentenceTimestamps[this.sentenceTimestamps.length - 1].end = this.audioDuration;
    }
    
    console.log('Sentence timestamps calculated:', this.sentenceTimestamps);
  }
  
  /**
   * 设置音频进度监听器
   * @private
   */
  _setupAudioProgressListener() {
    if (!this.audioManager) return;
    
    // 清理之前的监听器
    if (this.audioProgressListener) {
      try {
        this.audioManager.off('progress', this.audioProgressListener);
      } catch (e) {
        console.warn('Failed to remove previous progress listener:', e);
      }
    }
    
    // 创建新的进度监听器
    this.audioProgressListener = (progress) => {
      this._updateSubtitleByAudioProgress(progress);
    };
    
    // 添加事件监听器
    if (typeof this.audioManager.on === 'function') {
      this.audioManager.on('progress', this.audioProgressListener);
    } else if (typeof this.audioManager.addEventListener === 'function') {
      this.audioManager.addEventListener('progress', this.audioProgressListener);
    }
  }
  
  /**
   * 根据音频进度更新字幕
   * @private
   * @param {number} progress - 音频进度（0-1之间的值）
   */
  _updateSubtitleByAudioProgress(progress) {
    if (!this.isSyncing || this.sentences.length === 0) return;
    
    // 计算当前播放时间（秒）
    const currentTime = progress * this.audioDuration;
    
    // 找到当前应该显示的句子
    const sentenceIndex = this._findCurrentSentenceIndex(currentTime);
    
    // 如果句子索引变化，更新显示
    if (sentenceIndex !== this.currentSentenceIndex) {
      this.currentSentenceIndex = sentenceIndex;
      this._showCurrentSentence();
    }
  }
  
  /**
   * 找到当前应该显示的句子索引
   * @private
   * @param {number} currentTime - 当前播放时间（秒）
   * @returns {number} 句子索引
   */
  _findCurrentSentenceIndex(currentTime) {
    for (let i = this.sentenceTimestamps.length - 1; i >= 0; i--) {
      if (currentTime >= this.sentenceTimestamps[i].start) {
        return i;
      }
    }
    return 0;
  }
  
  /**
   * 显示当前句子
   * @private
   */
  _showCurrentSentence() {
    if (!this.isSyncing || this.sentences.length === 0) return;
    
    const currentSentence = this.sentences[this.currentSentenceIndex];
    
    // 更新Canvas渲染
    if (this.canvasRenderer) {
      this.canvasRenderer.drawText(currentSentence);
    }
    
    // 确保更新3D纹理，使字幕在XR环境中显示
    if (this.texturePlaneManager) {
      this.texturePlaneManager.updateTexture();
      this.texturePlaneManager.showSubtitle();
    }
    
    console.log(`Showing sentence ${this.currentSentenceIndex + 1}/${this.sentences.length}: ${currentSentence}`);
    
    // 触发句子更新事件
    this._dispatchEvent('sentenceChanged', {
      sentence: currentSentence,
      index: this.currentSentenceIndex,
      total: this.sentences.length
    });
  }
  
  /**
   * 重置同步状态
   * @private
   */
  _resetSyncState() {
    this.isSyncing = false;
    this.sentences = [];
    this.currentSentenceIndex = 0;
    this.sentenceTimestamps = [];
    this.audioDuration = 0;
    
    // 清理音频进度监听器
    if (this.audioProgressListener && this.audioManager) {
      try {
        if (typeof this.audioManager.off === 'function') {
          this.audioManager.off('progress', this.audioProgressListener);
        } else if (typeof this.audioManager.removeEventListener === 'function') {
          this.audioManager.removeEventListener('progress', this.audioProgressListener);
        }
      } catch (e) {
        console.warn('Failed to remove progress listener:', e);
      }
      this.audioProgressListener = null;
    }
  }
}

// 导出单例实例
const subtitleContentManager = new SubtitleContentManager();
export default subtitleContentManager;